﻿#include "webcamframesource.h"
#include <termio.h>
#include <sys/select.h>

#define SINK_PORT 9554

int getch(void)
{
    fd_set rfds;
    struct timeval tv;
    struct termios tm, tm_old;
    int ch = -1;

    if(tcgetattr(0, &tm_old) < 0)//保存现在的终端设置
	return -1;
    tm = tm_old;
    cfmakeraw(&tm);//更改终端设置为原始模式，该模式下所有的输入数据以字节为单位被处理
    if(tcsetattr(0, TCSANOW, &tm))//设置上更改之后的设置
	return -1;

    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 1; //设置等待超时时间

    //检测键盘是否有输入
    if(select(1, &rfds, NULL, NULL, &tv) > 0)
	ch = getchar();

    if(tcsetattr(0, TCSANOW, &tm_old))//更改设置为最初的样子
	return -1;
    return ch;
}

int main(int argc, char *argv[])
{
    //创建任务调用器
    BasicTaskScheduler0 *scheduler = BasicTaskScheduler::createNew();
    //创建交互环境
    UsageEnvironment *_env = BasicUsageEnvironment::createNew(*scheduler);

    //创建RTSP服务器
    RTSPServer *rtspServer = RTSPServer::createNew(*_env, SINK_PORT);
    if (!rtspServer) {
        *_env << "Failed to create RTSP server: " << _env->getResultMsg() << "\n";
        ::exit(-1);
    }

    // add live stream
    WebcamMediaSubsession media(*_env);
    do {
        //获取摄像头
        ServerMediaSession *sms = ServerMediaSession::createNew(*_env, "webcam", 0, "Session from /dev/video0");
        sms->addSubsession(&media);
        rtspServer->addServerMediaSession(sms);

        char *url = rtspServer->rtspURL(sms);
        *_env << "using URL \"" << url << "\"\n";
        delete [] url;
    } while (0);

    //进行事件循环
    while(getch() != 'q')
        scheduler->SingleStep();

    return 0;
}
